<?php

class Mail_model extends CI_Model {
	public function __construct() {
		parent::__construct();
		$this->sub_table = 'ci_subscribers';
		$this->newsletter_table = 'ci_newsletters';
		$this->newsletter_record = 'ci_newsletter_records';
	}

	/**
	 * This function will query the database to check the latest article
	 * and then generate the html out of the view.
	 * @param int $newsletter_id
	 * @return mixed
	 */
	private function get_newsletter_html($newsletter_id = 999) {
		$query = $this
			->db
			->select('n.nid as node_id, n.title, n.created, fdb.body_summary, fpi.field_preview_image_fid,fm.uri')
			->from('node n')
			->join('field_data_body fdb','fdb.entity_id=n.nid')
			->join('field_data_field_preview_image fpi', 'fpi.entity_id=n.nid')
			->join('file_managed fm', 'fm.fid=fpi.field_preview_image_fid')
			->where('n.status', 1)
			->where('fdb.entity_type', 'node')
			->where('fpi.entity_type','node')
			->order_by('n.created', 'DESC')
			->limit(1)
			->get();

		$result = $query->result();

//		$view_data = array();
		foreach ($result as $key => $value) {
			$view_data['articles'][$key]['title'] = $value->title;
			$view_data['articles'][$key]['body'] = $value->body_summary;
			$view_data['articles'][$key]['nid'] = $value->node_id;
			$view_data['articles'][$key]['newsletter_id'] = $newsletter_id;
			$view_data['articles'][$key]['created'] = $value->created;
			$view_data['articles'][$key]['node_url'] = $this->alias->get_alias($value->node_id);
			$view_data['articles'][$key]['preview_image'] = load_image('article_banner',$value->uri);
		}

		$string = $this->parser->parse('admin/tpls/email_template_view', $view_data, TRUE);
		return $string;
	}

	/**
	 * This function will generate the html for the newsletter. Insert it to the database
	 * or update if required, and then update the newsletter id in the anchor tags
	 * @return mixed
	 */
	public function final_newsletter_html() {
//		checking if a record is present
		$check = $this->db->select('nid')->from($this->newsletter_table)->where('status',0)->get();
		if ($check->num_rows() > 1) {
			show_error('More than one pending newsletter', 500);
		}
		else {
			$query = $this->db->select()->from($this->newsletter_table)->where('status', 0)->get()->row_array();
			if ($query) {
				$this->update_newsletter_record($query['nid']);
			}
			else {
				dsm('Adding');
				$this->add_new_newsletter_record();
			}
		}
	}

	/**
	 * This function is mapping the table with subscriber id
	 * with the newsletter id and then status.
	 * @param $nid
	 */
	public function set_records($nid) {
		$subscribers = $this->db->select('sid')->from($this->sub_table)->where('status', 1)->where('removed', 0)->get();
		$subscribers = $subscribers->result_array();

		foreach ($subscribers as $row) {
			$data = array(
				'nid' => $nid,
				'sid' => $row['sid'],
				'status' => '0',
				'send' => NULL
			);
			$this->db->insert($this->newsletter_record,$data);
		}
	}

	/**
	 * This function will add a new row to the newsletter table.
	 */
	public function add_new_newsletter_record() {
		$newsletter_html = $this->get_newsletter_html();

		$data = array(
			'data' => $newsletter_html,
			'created' => time(),
			'status' => 0,
			'type' => 'new post'
		);

		$this->db->insert($this->newsletter_table, $data);
		$newsletter_id = $this->db->insert_id();

		$newsletter_html = $this->get_newsletter_html($newsletter_id);

		$this->mail_model->set_records($newsletter_id);

		echo $newsletter_html;
	}

	/**
	 * This function will update the newsletter table's unsent newsletter.
	 * @param $newsletter_id
	 */
	public function update_newsletter_record($newsletter_id) {
		$newsletter_html = $this->get_newsletter_html($newsletter_id);

		$data = array(
			'data' => $newsletter_html,
			'created' => time(),
			'status' => 0,
			'type' => 'new post'
		);

		$this->db->where('nid', $newsletter_id);
		$this->db->update($this->newsletter_table, $data);

		dsm($data,1);
	}

	public function get_subscribers($newsletter_id) {
		$result = $this->db
			->select()
			->from($this->newsletter_record . ' nr')
			->join($this->sub_table . ' s', 's.sid = nr.sid')
			->where('nid', $newsletter_id)
			->get()
			->result();

		$email_address = array();
		foreach ($result as $subscriber) {
			$email_address[] = $subscriber->email;
		}

		return $email_address;
	}

	public function send_mail($to, $subject, $body) {
		$from = "amitavroy@gmail.com";
//		$this->send_email_using_gmail($to, $from, $subject, $body);
		$this->send_email_using_gmail($to, $from, $subject, $body);
	}

	/**
	 * This function will be used for testing purpose.
	 * @param $to
	 * @param $from
	 * @param $subject
	 * @param $body
	 */
	private function testing_mail($to, $from, $subject, $body) {
		echo 'TO: ' . $to . '<br />' . 'From: ' . $from . '<br />' . 'Body: <br />' . $body;
	}

	/**
	 * This is a running function and should be used only on live server.
	 * @param $to
	 * @param $from
	 * @param $subject
	 * @param $body
	 */
	private function send_email_using_gmail($to, $from, $subject, $body) {
		$this->load->library('mail');
		$host = "ssl://smtp.gmail.com";
		$port = "465";
		$username = "amitavroy@gmail.com";  //<> give errors
		$password = "brisinger";
		$to = 'amitavroy@gmail.com';

		$headers = array (
			'From' => $from,
			'To' => $to,
			'Subject' => $subject
		);

		$smtp = Mail::factory('smtp',
			array ('host' => $host,
				'port' => $port,
				'auth' => true,
				'username' => $username,
				'password' => $password
			)
		);

		$mail = $smtp->send($to, $headers, $body);

		if (PEAR::isError($mail)) {
			echo("<p>" . $mail->getMessage() . "</p>");
		}
		else {
			echo("<p>Message successfully sent!</p>");
		}
	}
}